package com.ydh.host.base;


import android.util.Log;

import com.ydh.host.core.common.INetworkRequiredInfo;

import java.util.HashMap;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 接口通用使用方式
 *
 * @author 13001
 */
public abstract class BaseNetworkApi {

    private static final String TAG = BaseNetworkApi.class.getSimpleName();

    private static HashMap<String, Retrofit> retrofitHashMap = new HashMap<>();
    private static INetworkRequiredInfo iNetworkRequiredInfo;
    private static OkHttpClient mOkHttpClient;

    /**
     * 接口请求参数配置
     *
     * @param requiredInfo
     */
    public static void init(INetworkRequiredInfo requiredInfo) {
        iNetworkRequiredInfo = requiredInfo;
    }

    public static <T> T getServer(Class<T> service) {
        if (isINetworkRequiredInfo()) {
            Log.e(TAG, "getServer: 网络参数未配置");
            return null;
        }
        return getRetrofit(service).create(service);
    }

    /**
     * @param service
     * @param <T>     接口类型
     * @return Retrofit 对象
     */
    private static <T> Retrofit getRetrofit(Class<T> service) {
        Retrofit retrofit = retrofitHashMap.get(iNetworkRequiredInfo.getBaseUrl() + service.getName());
        if (retrofit != null) {
            return retrofit;
        }
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(iNetworkRequiredInfo.getBaseUrl());
        builder.client(getOkHttpClient());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        retrofit = builder.build();
        retrofitHashMap.put(iNetworkRequiredInfo.getBaseUrl() + service.getName(), retrofit);
        return retrofit;
    }

    /**
     * @return OkHttpClient对象
     */
    private static OkHttpClient getOkHttpClient() {
        if (mOkHttpClient != null) {
            return mOkHttpClient;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (iNetworkRequiredInfo.isDebug()) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }
        mOkHttpClient = builder.build();
        return mOkHttpClient;
    }

    /**
     * @return 检测网络配置状态
     */
    public static boolean isINetworkRequiredInfo() {
        boolean status = iNetworkRequiredInfo == null;
        if (status) {
            Log.e(TAG, "isINetworkRequiredInfo: 未初始化");
        }
        return status;
    }

}
